package com.leyou.controller;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.entity.Cart;
import com.leyou.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     *
     * @param cart
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> addCart(@RequestBody Cart cart) {
        this.cartService.addCart(cart);
        return ResponseEntity.ok().build();
    }

    /**
     * 批量新增，
     * 当用户登录时，我们就将用户在未登录状态下添加到购物车的商品一次性添加到redis中
     * @param cartList
     * @return
     */
    @PostMapping("list")
    public ResponseEntity<Void> addCartList(@RequestBody List<Cart> cartList) {
        this.cartService.addCartList(cartList);
        return ResponseEntity.ok().build();

    }

    /**
     * 查询购物车的商品列表
     *
     * @return
     */
    @GetMapping("list")
    public ResponseEntity<List<Cart>> queryCart() {
        List<Cart> cartList = this.cartService.queryCart();
        if (CollectionUtils.isEmpty(cartList)){
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return ResponseEntity.ok().body(cartList);
    }



    /**
     * 修改商品数量
     * @param id  商品id
     * @param num 商品修改后的数量
     * @return
     */
    @PutMapping
    public ResponseEntity<Void> updateCart(@RequestParam("id") Long id, @RequestParam("num") Integer num) {
        this.cartService.updateCart(id,num);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除商品
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public ResponseEntity<Void> deleteGoods(@PathVariable("id") Long id) {
        this.cartService.deleteGoods(id);
        return ResponseEntity.ok().build();
    }
}
